<?php

namespace App\Http\Model\Admin;

use Monolog\Logger;
use Monolog\Handler\StdoutHandler;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Config;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class ExcelEtl extends Model
{
    private $badData;

    public function __construct(){
        $this->badData['reason'];
    }

    public function etl($data)
    {
        $this->badData['reason'] = null;

    	$data = $this->basicEtl($data);

    	$phone = $data[0];

        if (!is_numeric($phone)) {
            $this->handleBadDate(Config::get('excel.bad_reason.phoneError'));
        }


    	$imei = $data[1];
    	$idfa = $data[2];
    	$city = $data[3];

    	// 搜索词
    	$searchTerm = $data[4];
    	// 用户动作
    	$action = $data[5];
    	// 房源类型
    	$pageType = $data[6];
    	// 访问时间
    	$visitTime = $data[7];
    	//echo $data[7];
    	// 省份
    	$houseProvince = $data[8];
    	// 地市
    	$houseCity = $data[9];
    	// 房源名称
    	$houseName = $data[10];
    	// 小区名称
    	$boroughNameSource = $data[11];
    	$boroughName = $boroughNameSource;

    	// 单价
    	$unitPrice = $data[12];

    	// 总价
    	$totalPrice = $data[13];

    	// 户型
    	$houseRoom = $data[14];

    	// 面积
    	$houseTotalArea = $data[15];

    	// 朝向
    	$houseToward = $data[16];

    	// 楼层
    	$houseFloor = $data[17];

    	// 装修
    	$houseFitment = $data[18];

    	// 建筑类型
    	$buildingType = $data[19];

    	// 住宅类型
    	$houseType = $data[20];

    	// 产权性质
    	$propertyRight = $data[21];

    	// 地址
    	$houseAddress = $data[22];


    	// 开始数据清洗
    	$phone = $this->etlPhone($phone);
        if (! $phone) {
            $this->handleBadDate(Config::get('excel.bad_reason.phoneError'));
        }

        $houseCityEtl = $this->etlCity($houseCity);
        if (! $houseCityEtl) {
            $this->handleBadDate(Config::get('excel.bad_reason.cityError'));
        }else{
            //只有城市合法，才做小区ETL
            $boroughEtl = $this->etlBorough($houseCityEtl['en'], $boroughName);
            if(isset($boroughEtl['status']) && false == $boroughEtl['status']){
                $this->handleBadDate(Config::get('excel.bad_reason.boroughError'));
            }
        }

    	$unitPrice = $this->etlUnitPrice($unitPrice);
    	$totalPrice = $this->etlTotalPrice($totalPrice);
    	$houseRoom = $this->etlHouseRoom($houseRoom);
    	$houseFitment = $this->etlHouseFitment($houseFitment);
    	$houseTotalArea = $this->etlHouseTotalArea($houseTotalArea);

    	// 数据清洗结束
    	$result = array(
    		"phone" => $phone,
    		"appName" => 'zgzf',
    		"city" => $houseCityEtl['en'],
    		"platform_type" => 0,
    		"data_status" => 1,
    		"data_input" => 1,
    		"source_id" => 1,
    		"imei" => $imei,
    		"idfa" => $idfa,
    		"user_behavior" => '',
    		"search_term" => $searchTerm,
    		"purpose_desc" => '',
    		"page_type" => $pageType,
    		//"visit_time" => $visitTime,
    		"house_province" => $houseProvince,
    		"house_city" => $houseCity,
    		"cityarea_id" => $boroughEtl['cityAreaId'],
    		"cityarea_name" => $boroughEtl['cityAreaName'],
    		"cityarea_name_source" => $boroughNameSource,
    		"cityarea2_id" => $boroughEtl['cityArea2Id'],
    		"cityarea2_name" => $boroughEtl['cityArea2Name'],
    		"cityarea2_name_source" => $boroughNameSource,
    		"house_name" => $houseName,
    		"unit_price" => $unitPrice,
    		"house_price" => $totalPrice,
    		"house_room" => $houseRoom,
    		"house_hall" => 0,
    		"house_toilet" => 0,
    		"borough_name" => $boroughName,
    		"borough_name_source" => $boroughNameSource,
    		"borough_id" => $boroughEtl['boroughId'],
    		"house_totalarea" => $houseTotalArea,
    		"house_toward" => intval($houseToward),
    		"house_topfloor" => 0,
    		"house_floor" => $houseFloor,
    		"house_fitment" => $houseFitment,
    		"building_type" => $buildingType,
    		"house_type" => $houseType,
    		"property_right" => $propertyRight,
    		"house_address" => '',
    		"created_at" => date('Y-m-d H:i:s', time()),
    		);

        if(empty($this->badData['reason'])){
            return $result;
        }else{

            $bad_data['data'] = json_encode($result);
            $bad_data['reason'] = $this->badData['reason'];
            $bad_data['channel'] = 1;
            DB::table('bad_data')->insert($bad_data);
            return false;
        }

    }

    // 过滤池
    private function etlPhone($phone, $filterPool = [])
    {
        if (count($filterPool) > 0 && in_array($phone, $filterPool)) {
            return false;
        }

        if (strlen($phone) != 11) {
            return false;
        }
        
    	return $phone;
    }


    private function etlImei($imei)
    {
    	return $imei;
    }

    private function etlCity($cityString)
    {
        $data = [
            'name' => '',
            'en' => ''
        ];

        if(empty($cityString)){
            return $data;
        }
        $en = '';
    	$cities = \Config::get('admin.cities');
    	$cityNameList = array_column($cities, 'name_cn');
    	$cityEnList = array_column($cities, 'name_en');
    	for($i=0;$i<count($cityNameList);$i++) {
    		if (strpos($cityNameList[$i], $cityString) !== false) {
    			$name = $cityNameList[$i];
    			$en = $cityEnList[$i];
    			break;
    		}
    	}

    	if ($en) {
            return $data = ['name' => $name, 'en' => $en];
    	}
    	else {
            return $data;
    	}
    }


    private function etlBorough($cityEn, $boroughName)
    {
        $key = 'dmp_borough_name_city_'.$cityEn. '_uid:' . md5($boroughName);

        $data = \MyRedis::get($key);
    	// redis中没有查到则走api接口
    	if (! $data) {
    		$url = 'http://data.zhuge888.com/Borough/api/getBoroughData?city='.$cityEn.'&id=&name='.$boroughName;
            $result = $this->curl_get($url);
            $result = json_decode($result, true);
            if (! is_array($result) || $result['code'] != 200) {
            	return array(
                    'status' => false,
                    'cityAreaId' => 0,
                    'cityAreaName' => '',
                    'cityArea2Id'=>0,
                    'cityArea2Name' => '',
                    'boroughId' => 0,
                    );
            }


            $boroughId = $result['data']['id'];
            $boroughName = $result['data']['name'];

            $cityAreaId = $result['data']['cityarea']['cityarea_id'];
            $cityAreaName = $result['data']['cityarea']['cityarea_name'];

            $cityArea2Id = $result['data']['cityarea2'][0]['cityarea2_id'];
            $cityArea2Name = $result['data']['cityarea2'][0]['cityarea2_name'];

            $data = array('boroughId' => $boroughId, 'boroughName' => $boroughName, 'cityAreaId' => $cityAreaId, 'cityAreaName' => $cityAreaName, 'cityArea2Id' => $cityArea2Id, 'cityArea2Name' => $cityArea2Name);

            \MyRedis::set($key, json_encode($data));
    	}
    	else {
    		$data = json_decode($data, true);
    	}

    	return $data;
    }


    private function etlUnitPrice($price)
    {
    	return (int)$price;
    }


    private function etlTotalPrice($totalPrice)
    {
    	return (int)$totalPrice;
    }


    private function etlHouseRoom($houseRoom)
    {
    	return (int)$houseRoom;
    }


    private function etlHouseTotalArea($houseTotalArea)
    {
    	return (int)$houseTotalArea;
    }

    private function etlHouseFitment($houseFitment)
    {
        if ($houseFitment == '') {
            return 0;
        }
    	if (strpos('毛', $houseFitment) !== false) {
    		return 1;
    	}
    	else if (strpos('简', $houseFitment) !== false) {
    		return 2;
    	}
    	else if (strpos('中', $houseFitment) !== false) {
    		return 3;
    	}
    	else if (strpos('精', $houseFitment) !== false) {
    		return 4;
    	}
    	else {
    		return 0;
    	}
    }

    private function basicEtl($data)
    {
    	foreach ($data as &$elem) {
            if ($elem == null) {
                $elem = '';
            }

    		if ($elem == 'NULL') {
    			$elem = '';
    		}

//            if (strlen($elem) > 20) {
//                $elem = '';
//            } //todo 是否要做长度判断
    	}

    	return $data;
    }

    public function pushToKafka($data)
    {

    }

    private function curl_get($url)
	{   
	    $ch_curl = curl_init();
	    curl_setopt ($ch_curl, CURLOPT_TIMEOUT, 60000);
	    curl_setopt($ch_curl, CURLOPT_SSL_VERIFYPEER, 0);
	    curl_setopt ($ch_curl, CURLOPT_HEADER,false);
	    curl_setopt($ch_curl, CURLOPT_HTTPGET, 1);
	    curl_setopt($ch_curl, CURLOPT_RETURNTRANSFER,true);
	    curl_setopt ($ch_curl, CURLOPT_URL,$url);
	    $str  = curl_exec($ch_curl);
	    curl_close($ch_curl);
    	return $str;
    }

    //处理数据错误原因
    private function handleBadDate($reason){
        $this->badData['reason'] .= $reason;
    }

}
